<?php
/**
 * @author littlexiang
 * @version $Id: Dispatcher.php 685 2009-08-03 06:28:25Z songxiang $
 */

class Dispatcher {
    
    public static function dispatch () {
        $uri = $_SERVER['REQUEST_URI'];
        
        $uri = Router::routing($uri);
        
        $return = Uri::parse($uri);
        
        $sub_config = require APP_PATH . 'config' . DIRECTORY_SEPARATOR . 'config.php';
        Config::$config = array_merge(Config::$config, $sub_config);
        
        require_once APP_PATH . 'bootstrap.php';
        
        Context::set($return);
        
        self::forward($return['controller'], $return['action']);

    }
    
    public static function forward ($controller = '', $action = '') {
        
        $controllerName = $controller ? ucfirst(strtolower($controller)) . 'Controller': 'IndexController';
        $actionName = $action ? strtolower($action) . 'Action' : 'IndexAction';
        
        $filename = APP_PATH . 'controller' . DIRECTORY_SEPARATOR . $controllerName . '.php';
        if (is_file($filename) && is_readable($filename)) {
            require_once $filename;
        } else {
            throw new Dispatcher_Exception('Could not find file ' . $filename);
        }
        
        if (class_exists($controllerName)) {
            $object_controller = new $controllerName($controller, $action);
        } else {
            throw new Dispatcher_Exception('Could not find Class ' . $controllerName);
        }
        
        if (method_exists($object_controller, $actionName)) {
            $preAction = 'pre' . $actionName;
            if (method_exists($object_controller, $preAction)) {
                $object_controller->$preAction();
            }
            
            $tpl = $object_controller->$actionName();
  
            Context::set('tpl', $tpl);
        
        } else {
            throw new Dispatcher_Exception('Could not find Method ' . $actionName . ' in Controller ' . $controllerName);
        }
    
    }
}